package com.itheima.bos.web.action.base;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.itheima.bos.domain.base.Area;
import com.itheima.bos.domain.base.FixedArea;
import com.itheima.bos.domain.base.SubArea;
import com.itheima.bos.service.base.SubAreaService;
import com.itheima.bos.web.action.common.BaseAction;

@Namespace("/")
@ParentPackage("json-default")
@Scope("prototype")
@Controller
public class SubAreaAction extends BaseAction<SubArea> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Autowired
	private SubAreaService subAreaService;

	/*
	 * 批量导入
	 */
	private File file;
	private String fileFileName;

	public void setFile(File file) {
		this.file = file;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	@Action("subarea_batchImport")
	public String batchImport() throws Exception {

		List<SubArea> subareas = new ArrayList<SubArea>();

		if (fileFileName.endsWith(".xls")) {
			HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(file));
			HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
			for (Row row : hssfSheet) {
				areaBuilder(subareas, row);
			}

		} else if (fileFileName.endsWith(".xlsx")) {
			XSSFWorkbook xssfWorkbook = new XSSFWorkbook(file);
			XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
			for (Row row : xssfSheet) {
				areaBuilder(subareas, row);
			}
		}

		subAreaService.saveBatch(subareas);

		return NONE;
	}

	private void areaBuilder(List<SubArea> subareas, Row row) {

		if (row.getRowNum() == 0) {
			return;
		}
		if (row.getCell(0) == null && StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
			return;
		}
		SubArea subArea = new SubArea();
		FixedArea fixedArea = new FixedArea();
		fixedArea.setId(row.getCell(1).getStringCellValue());
		Area area = new Area();
		area.setId(row.getCell(2).getStringCellValue());

		subArea.setId(row.getCell(0).getStringCellValue());
		subArea.setFixedArea(fixedArea);
		subArea.setArea(area);
		subArea.setKeyWords(row.getCell(3).getStringCellValue());
		subArea.setStartNum(row.getCell(4).getStringCellValue());
		subArea.setEndNum(row.getCell(5).getStringCellValue());
		subArea.setSingle(row.getCell(6).getStringCellValue());
		subArea.setAssistKeyWords(row.getCell(7).getStringCellValue());

		subareas.add(subArea);
	}

	/*
	 * 查询分区
	 */
	@Action(value = "subarea_pageQuery", results = { @Result(name = "success", type = "json") })
	public String PageQuery() {

		Pageable pageable = new PageRequest(page - 1, rows);
		Specification<SubArea> specification = new Specification<SubArea>() {

			List<Predicate> list = new ArrayList<Predicate>();

			@Override
			public Predicate toPredicate(Root<SubArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

				// 省
				Join<Object, Object> areaRoot = root.join("area", JoinType.INNER);
				if (model.getArea() != null && StringUtils.isNotBlank(model.getArea().getProvince())) {
					Predicate p1 = cb.like(areaRoot.get("province").as(String.class),
							"%" + model.getArea().getProvince() + "%");
					list.add(p1);
				}
				// 市
				if (model.getArea() != null && StringUtils.isNotBlank(model.getArea().getCity())) {
					Predicate p2 = cb.like(areaRoot.get("city").as(String.class),
							"%" + model.getArea().getCity() + "%");
					list.add(p2);
				}
				// 区
				if (model.getArea() != null && StringUtils.isNotBlank(model.getArea().getDistrict())) {
					Predicate p3 = cb.like(areaRoot.get("district").as(String.class),
							"%" + model.getArea().getDistrict() + "%");
					list.add(p3);
				}
				// 定区编码
				Join<Object, Object> fixedAreaRoot = root.join("fixedArea", JoinType.INNER);
				if (model.getFixedArea() != null && StringUtils.isNotBlank(model.getFixedArea().getId())) {
					Predicate p4 = cb.like(fixedAreaRoot.get("id").as(String.class),
							"%" + model.getFixedArea().getId() + "%");
					list.add(p4);
				}
				// 关键字
				if (StringUtils.isNotBlank(model.getKeyWords())) {
					Predicate p5 = cb.like(root.get("keyWords").as(String.class), "%" + model.getKeyWords() + "%");
					list.add(p5);
				}

				return cb.and(list.toArray(new Predicate[0]));
			}
		};
		// 调用业务层
		Page<SubArea> pageData = subAreaService.findPageData(specification, pageable);
		pushPageDataToValueStack(pageData);

		return SUCCESS;
	}
}
